let express = require('express')
let serve = express()

serve.use(express.static('./static'))

serve.use(express.json(), express.urlencoded())

const jwt = require('jsonwebtoken');
// token的秘钥
let secret = 'wssb996'
// 设置白名单
let white = ['/api/user/login','/api/user/register', ]
// 统一验证token
serve.use((req, res, next) => {
    let url = req._parsedUrl.pathname;
    if (white.includes(url)|| url.includes('/api/user/check')) {
        next();
        return
    }
    let token = req.headers.authorization;
    // 解析token
    jwt.verify(token, secret, (err, decode) => {
        if (err) {
            res.send({
                code: 400,
                msg: '未登录a'
            })
            return
        }
        // 把token解析出来之后，想要在其他的中间件使用，可以把解密出来的用户信息存储到req请求对象中
        let info = {
            ...decode
        }
        req.info = info;
        // 继续下一步，真正请求的接口
        next();
    })
})
// 用户模块
let user = require('./api/user')
serve.use('/api/user', user)

serve.listen(9091, () => {
    console.log('后端9091端口已经开启');
})